package com.gxpt.app.view;

import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseActivity;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.bean.createtime_my_bean;
import com.gxpt.app.view.myview.pickerview.PickerView;
import com.utils.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * Created by dufeng on 2017/8/4.
 */

@ContentView(R.layout.activity_createtime_sub)
public class Activity_createtime_sub extends BaseActivity {

    @ViewInject(R.id.toback)
    Button toback;

    @ViewInject(R.id.txt_title)
    TextView txt_title;

    @ViewInject(R.id.txt_right)
    TextView txt_right;

    @ViewInject(R.id.txt_right2)
    TextView txt_right2;

    @ViewInject(R.id.txt_P_LOSE)
    TextView txt_P_LOSE;

    @ViewInject(R.id.txt_T_B)
    TextView txt_T_B;

    @ViewInject(R.id.txt_T_E)
    TextView txt_T_E;

    @ViewInject(R.id.txt_price)
    TextView txt_price;


    //timer
    Dialog dialog;
    PickerView pickerView_y,pickerView_m,pickerView_d;
    String cy=null,cm=null,cd=null;



    double P_LOSE = 0;
    double P_SUM  = 0;

    double P_SUM_list  = 0;//列表总价
    String T_B = "";
    String T_E = "";
    double current_price = 0;
    boolean IS_ADD = false;//是不是添加
    int index_list = 0;

    String jsonData = "";


    String json_submit = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);


        Bundle b = getIntent().getBundleExtra("DATA");
        if(b != null){
            P_SUM = b.getDouble("P_SUM");
            P_LOSE = b.getDouble("P_LOSE");
            jsonData = b.getString("Current_json");
            IS_ADD = b.getBoolean("IS_ADD");


            index_list = b.getInt("index_list");
            T_B    = b.getString("T_B");
            T_E    = b.getString("T_E");
            current_price = b.getDouble("current_price");

//            Logger.i("  索引 index_list = "+index_list);
//            Logger.i("  剩余 P_LOSE = "+P_LOSE);
        }
        initView();
    }

    @Override
    public void initView() {
        txt_title.setText(getString(R.string.txt_tianjiaxiangmugongqi));
        txt_right.setVisibility(View.VISIBLE);
        txt_P_LOSE.setText(getValue(P_LOSE));
        txt_T_B.setText(T_B);
        txt_T_E.setText(T_E);
        txt_price.setText(""+current_price);

        if(IS_ADD){
            txt_right2.setVisibility(View.GONE);
            txt_price.setText(""+P_LOSE);
        }else{
            txt_right2.setVisibility(View.VISIBLE);
        }
    }

    private String getValue(Double de){
        return ""+de+"元";
    }


    @Override
    public void initData() {

    }

    @Event(value={R.id.toback,R.id.txt_right,R.id.txt_T_B,R.id.txt_T_E,R.id.txt_right2})
    private void getEvent(View view){
        switch(view.getId()){

            case R.id.toback:
                closeActivity();
                break;
            case R.id.txt_right:
                if(checkViews()){
                    try{
                        if(Double.valueOf(txt_price.getText().toString())!=0.0){
                            if(IS_ADD){
                                if(Double.valueOf(txt_price.getText().toString()) <= P_LOSE){
                                    String data = createJson(txt_T_B.getText().toString(),
                                            txt_T_E.getText().toString(),
                                            Double.parseDouble(txt_price.getText().toString()),
                                            false,0);
                                    EventBus.getDefault().post(new MessageEvent(
                                            Constant.ACTION_to_gq,
                                            data,""+json_submit,""+P_SUM_list));
                                    closeActivity();
                                }else{
                                    Toast.makeText(context,""+getResources().getString(R.string.alert_not_price),Toast.LENGTH_LONG).show();
                                }
                            }else{
                                if(Double.valueOf(txt_price.getText().toString()) <= (P_LOSE+Double.valueOf(txt_price.getText().toString()))){
                                    String data = createJson(txt_T_B.getText().toString(),
                                            txt_T_E.getText().toString(),
                                            Double.parseDouble(txt_price.getText().toString()),
                                            false,0);
                                    EventBus.getDefault().post(new MessageEvent(
                                            Constant.ACTION_to_gq,
                                            data,""+json_submit,""+P_SUM_list));
                                    closeActivity();
                                }else{
                                    Toast.makeText(context,""+getResources().getString(R.string.alert_not_price3),Toast.LENGTH_LONG).show();
                                }
                            }
                        }else{
                            Toast.makeText(context,""+getResources().getString(R.string.alert_not_price2),Toast.LENGTH_LONG).show();
                        }

                    }catch (Exception e){
                        e.printStackTrace();
                    }

                }
                break;
            case R.id.txt_right2:
                String data = createJson("",
                        "",
                        0.0,
                        true,index_list);

                EventBus.getDefault().post(new MessageEvent(
                        Constant.ACTION_to_gq,
                        data,""+json_submit,""+P_SUM_list));
                closeActivity();
                break;
            case R.id.txt_T_B:
                showTimeDialog(txt_T_B);
                break;
            case R.id.txt_T_E:
                showTimeDialog(txt_T_E);
                break;
        }
    }

    private boolean checkViews(){
        if(txt_price.getText().toString().isEmpty() || txt_T_B.getText().toString().isEmpty() || txt_T_E.getText().toString().isEmpty()){
            Toast.makeText(context,""+getResources().getString(R.string.alert_putisnotnull),Toast.LENGTH_LONG).show();
            return false;
        }else{
            return true;
        }

    }


    private String  createJson(String t_b,String t_e,double price,boolean isDel,int del_index){
            try {
                List<createtime_my_bean.stage> list = null;
                if(jsonData.isEmpty()){
                    list = new ArrayList<createtime_my_bean.stage>();
                }else{
                    createtime_my_bean data = new Gson().fromJson(jsonData, createtime_my_bean.class);
                    list = data.data;
                }

                if(isDel){//是否是删除操作
                    list.remove(del_index);
                }else{
                    if(IS_ADD){
                        Logger.i("添加");
                        createtime_my_bean a = new createtime_my_bean();
                        createtime_my_bean.stage newData = a.new stage();
                        newData.t_b = t_b;
                        newData.t_e = t_e;
                        newData.price = price;
                        list.add(newData);
                    }else{
                        Logger.i("修改");
                        list.get(index_list).t_b = t_b;
                        list.get(index_list).t_e = t_e;
                        list.get(index_list).price = price;
                    }
                }



                JSONObject main = new JSONObject();
                JSONArray ja = new JSONArray();

                JSONObject main2 = new JSONObject();
                JSONObject ja2   = new JSONObject();
                int count = 0;

                Logger.i("list.size() = "+list.size());

//                for(int c=0; c<=list.size();c++){
//                    JSONObject jo = new JSONObject();
//                    jo.put("t_b", list.get(c).t_b);
//                    jo.put("t_e", list.get(c).t_e);
//                    jo.put("price",list.get(c).price);
//                    ja.put(jo);
//                    //
//                    P_LOSE = P_LOSE - list.get(c).price;
//                    //
//                    JSONArray jy1 = new JSONArray();
//                    jy1.put(list.get(c).t_b);
//                    jy1.put(list.get(c).t_e);
//                    jy1.put(list.get(c).price);
//                    jy1.put(P_LOSE);
//
//                    ja2.put(""+c,jy1);
//                }

                for (createtime_my_bean.stage d : list) {

                    JSONObject jo = new JSONObject();
//                    jo.put("t_b", d.t_b);
//                    jo.put("t_e", d.t_e);
//                    jo.put("price",d.price);
                    jo.put("t_b", list.get(count).t_b);
                    jo.put("t_e", list.get(count).t_e);
                    jo.put("price",list.get(count).price);

                    //
//                    P_SUM_list  = P_SUM_list + list.get(count).price;
//                    P_SUM       = P_SUM - list.get(count).price;

                    P_SUM_list  = AppUtils.double_sum(P_SUM_list,list.get(count).price);
                    P_SUM       = AppUtils.double_sub(P_SUM,list.get(count).price) ;


                    Logger.i(""+ AppUtils.double_sub(0.03,0.01));
                    //

                    ja.put(jo);

                    //
                    JSONArray jy1 = new JSONArray();
                    jy1.put(d.t_b);
                    jy1.put(d.t_e);
                    jy1.put(d.price);
                    jy1.put(P_SUM);

                    ja2.put(""+count,jy1);

                    count++;

                }
                main.put("data",ja);
                main2.put("stage_content",ja2);


                Logger.e("ja2 = "+ja2.toString());
                json_submit = ja2.toString();



                return main.toString();
            } catch (Exception e) {
                e.printStackTrace();
                Logger.e("error");
                return "";
            }

    }

    ////////////////////////////////////////////////
    public void showTimeDialog(final TextView textview){

        dialog=new Dialog(context,R.style.customDialogStyle);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view= LayoutInflater.from(context).inflate(R.layout.dialog_receive_time, null);
        dialog.setContentView(view);

        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        int day = calendar.get(Calendar.DATE);

        cy = ""+year;
        cm = ""+month;
        cd = ""+day;

        pickerView_y =(PickerView) view.findViewById(R.id.date_year);
        pickerView_m =(PickerView) view.findViewById(R.id.date_month);
        pickerView_d =(PickerView) view.findViewById(R.id.date_day);

//
//
        String[] date_time_y={"2017","2018","2019","2020","2021"};
        String[] date_time_m_big = { "1", "3", "5", "7", "8", "10", "12" };
        String[] date_time_m_little = { "4", "6", "9", "11" };



        final List<String> data_y=new ArrayList<String>(Arrays.asList(date_time_y));//年
        final List<String> data_m_big=new ArrayList<String>(Arrays.asList(date_time_m_big));//月
        final List<String> data_m_little=new ArrayList<String>(Arrays.asList(date_time_m_little));//月

        final List<String> data_m=new ArrayList<String>(Arrays.asList(getList(1,12)));//月



        pickerView_y.setData(data_y);
        pickerView_y.setSelected(1);

        pickerView_m.setData(data_m);
        pickerView_m.setSelected(month);



//
        if (data_m_big.contains(String.valueOf(month))) {
            pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,31))));
            pickerView_d.setSelected(day);
        } else if (data_m_little.contains(String.valueOf(month))) {
            pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,30))));
            pickerView_d.setSelected(day);
        } else {
// 闰年
            if (isLeapYear(year)){
                pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,29))));
                pickerView_d.setSelected(day);
            }else{
                pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,28))));
                pickerView_d.setSelected(day);
            }
        }

        pickerView_y.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text,int index) {
                cy = text;
                cd = "1";
                if (data_m_big.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,31))));
                    pickerView_d.setSelected(1);
                } else if (data_m_little.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,30))));
                    pickerView_d.setSelected(1);
                } else {
// 闰年
                    if (isLeapYear(Integer.parseInt(cy))){
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,29))));
                        pickerView_d.setSelected(1);
                    }else{
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,28))));
                        pickerView_d.setSelected(1);
                    }
                }
            }
        });

        pickerView_m.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text,int index) {
                cm = text;
                cd = "1";
                if (data_m_big.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,31))));
                    pickerView_d.setSelected(1);
                } else if (data_m_little.contains(String.valueOf(cm))) {
                    pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,30))));
                    pickerView_d.setSelected(1);
                } else {
// 闰年
                    if (isLeapYear(Integer.parseInt(cy))){
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,29))));
                        pickerView_d.setSelected(1);
                    }else{
                        pickerView_d.setData(new ArrayList<String>(Arrays.asList(getList(1,28))));
                        pickerView_d.setSelected(1);
                    }
                }

            }
        });
        pickerView_d.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text,int index) {
                cd = text;
            }
        });



        view.findViewById(R.id.common_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        view.findViewById(R.id.common_sure).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                textview.setText(cy+"-"+cm+"-"+cd);
                dialog.dismiss();
            }
        });

        dialog.getWindow().setWindowAnimations(R.style.commonAnimDialogStyle);
        dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        dialog.show();
    }

    public String[] getList(int start,int end){
        String[] a = new String[end];
        for(int n=0;n < end;n++){
            a[n] = ""+(n+1);
        }
        return a;
    }

    /**
     * 描述：判断是否是闰年()
     * <p>(year能被4整除 并且 不能被100整除) 或者 year能被400整除,则该年为闰年.
     *
     * @param year 年代（如2012）
     * @return boolean 是否为闰年
     */
    public boolean isLeapYear(int year) {
        if ((year % 4 == 0 && year % 400 != 0) || year % 400 == 0) {
            return true;
        } else {
            return false;
        }
    }

}
